<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Socket.IO Demo</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .container {
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <h1>Socket.IO Demo Application</h1>
    <div class="container">
        <input type="text" id="ID_input">
        <button id="sendBtn">发送</button>
    </div>
    <ul id="msg_list">

    </ul>
    <script src="https://cdn.socket.io/4.8.1/socket.io.min.js"></script>
    <script>
        // 建立连接（自动识别WebSocket或降级方案）
        const socket = io('http://localhost:3000', {
            reconnectionAttempts: 5, // 重连尝试次数
            autoConnect: true       // 自动连接
        });

        socket.on('connect', () => {
            console.log('Connected to server');
        });

        // 监听服务端消息
        socket.on('chat message', (msg) => {
            console.log('收到服务端消息:', msg);
            // 追加元素 li
            const msg_list = document.getElementById('msg_list');
            const li = document.createElement('li');
            li.textContent = msg;
            msg_list.appendChild(li);
        });

        // 发送消息到服务端
        document.getElementById('sendBtn').addEventListener('click', () => {
            const msg = document.getElementById('ID_input').value;
            socket.emit('chat message', msg);
        });

        // 连接状态监听
        socket.on('connect', () => {
            console.log('已连接', socket.id);
        });

        socket.on('disconnect', () => {
            console.log('已断开');
        });
    </script>
</body>
</html>
